/* ========================================================================
 * Jquery and checked input
 *
 *  <div class="input-prepend">
 *    <span class="add-on"><label class="checkbox"><input type="checkbox" data-toggle="checkedinput"></label></span>
 *    <input  class="span2" placeholder="placeholder" type="text" data-type="date" value="2013-03-01">
 *  </div>
 *
 * ======================================================================== */


+function ($) { "use strict";

  var Checkedinput = function (element) {
    this.element = $(element);
    this.dataContainer = this.element.closest('div.input-prepend');
    this.dataInput = this.dataContainer.children('input');
    this.dataType = this.dataInput.attr('data-type');
    this.dataFormat = this.dataInput.attr('data-format');
    this.init();
  };

  Checkedinput.prototype.init = function () {
    //console.log('init');
    var value = this.dataInput.attr('value');
    if (value && value != '') {
      this.element[0].checked = true;
      this.dataInput[0].disabled = false;
    } else {
      this.element[0].checked = false;
      this.dataInput[0].disabled = true;
    }
  };

  Checkedinput.prototype.toggle = function () {
    //console.log('toggle');
    if(this.element[0].checked) {
      this.dataInput[0].disabled = false;
      if (!this.dataInput.val()) {
        var defaultValue = (this.dataType) ? this[this.dataType]() : '';
        this.dataInput.val(defaultValue);
      }
    } else {
      this.dataInput.val('');
      this.dataInput[0].disabled = true;
    }
  };

  Checkedinput.prototype.date = function () {
    //console.log('date');
    var d = new Date();
    var s =  this.dataFormat || 'yyyy-mm-dd';
    return s.replace('yyyy', d.getFullYear()).replace('mm',d.getMonth() + 1).replace('dd', d.getDate());
  };

  // Checkedinput PLUGIN DEFINITION
  // =====================
  var old = $.fn.checkedinput

  $.fn.checkedinput = function ( option ) {
    return this.each(function () {
      var $this = $(this)
      var data  = $this.data('bq.checkedinput')
      if (!data) $this.data('bq.checkedinput', (data = new Checkedinput(this)));
      if (typeof option == 'string') data[option]();
    })
  };

  $.fn.checkedinput.Constructor = Checkedinput;

  // Checkedinput NO CONFLICT
  // ===============
  $.fn.checkedinput.noConflict = function () {
    $.fn.checkedinput = old;
    return this;
  }

  // Checkedinput DATA-API
  // ============
  $(document).on('click.bq.checkedinput', '[data-toggle="checkedinput"]', function (e) {
    //e.preventDefault();
    $(this).checkedinput('toggle');
  });
  $(window).on('ready', function () {
    $('[data-toggle="checkedinput"]').each(function () {
      //e.preventDefault();
      $(this).checkedinput();
    })
  });
}(window.jQuery);
